package com.kaoshi.jeeweb.common.web.base;

import com.kaoshi.jeeweb.common.entity.AbstractEntity;
import com.kaoshi.jeeweb.common.persistence.BaseEntity;
import com.kaoshi.jeeweb.common.persistence.DataEntity;
import com.kaoshi.jeeweb.common.web.BaseController;
import com.kaoshi.myweb.common.lib.pagehelper.Page;
import com.kaoshi.myweb.common.lib.pagehelper.PageInfo;
import com.kaoshi.myweb.common.utils.DateUtils;
import com.kaoshi.myweb.common.utils.ReflectUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.beans.PropertyEditorSupport;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 基础的Controller,所有的Controller必须继承此类
 * 
 * @copyright {@link 9iu.org}
 * @author springrain<9iuorg@gmail.com>
 * @version 2013-03-19 11:08:15
 */
public class BaseGenericController<M extends DataEntity, ID extends Serializable> extends BaseController {
	public   Logger logger = LoggerFactory.getLogger(getClass());

	public String messageurl = "/common/message";

	public String message = "message";

	public String redirect = "redirect:";

	public String forward = "forward:";



	 /**
     * 实体类型
     */
    protected final Class<M> entityClass;

    private String viewPrefix;


    protected BaseGenericController() {
        this.entityClass = ReflectUtils.findParameterizedType(getClass(), 0);
        setViewPrefix(defaultViewPrefix());
    }


    /**
     * 设置通用数据
     *
     * @param model
     */
    protected void setCommonData(Model model) {
    }


    /**
     * 当前模块 视图的前缀
     * 默认
     * 1、获取当前类头上的@RequestMapping中的value作为前缀
     * 2、如果没有就使用当前模型小写的简单类名
     */
    public void setViewPrefix(String viewPrefix) {
        if (viewPrefix.startsWith("/")) {
            viewPrefix = viewPrefix.substring(1);
        }
        this.viewPrefix = viewPrefix;
    }

    public String getViewPrefix() {
        return viewPrefix;
    }

    protected M newModel() {
        try {
            return entityClass.newInstance();
        } catch (Exception e) {
            throw new IllegalStateException("can not instantiated model : " + this.entityClass, e);
        }
    }

    /**
     * 获取视图名称：
     *
     * @return
     */
    public String viewName(String suffixName) {
        return getViewPrefix() + suffixName;
    }

    /**
     * 共享的验证规则
     * 验证失败返回true
     *
     * @param m
     * @param result
     * @return
     */
    protected boolean hasError(M m, BindingResult result) {
        Assert.notNull(m);
        return result.hasErrors();
    }

    /**
     * @param backURL null 将重定向到默认getViewPrefix()
     * @return
     */
    protected String redirectToUrl(String backURL) {
        if (StringUtils.isEmpty(backURL)) {
            backURL = getViewPrefix();
        }
        if (!backURL.startsWith("/") && !backURL.startsWith("http")) {
            backURL = "/" + backURL;
        }
        return "redirect:" + backURL;
    }

    protected String defaultViewPrefix() {
        String currentViewPrefix = "";
        RequestMapping requestMapping = AnnotationUtils.findAnnotation(getClass(), RequestMapping.class);
        if (requestMapping != null && requestMapping.value().length > 0) {
            String pathValue = requestMapping.value()[0];
			if(pathValue.endsWith("/")){
				pathValue = pathValue.substring(0, pathValue.length() - 1);
			}
			//去掉${adminpath}/部分
			currentViewPrefix = "modules" + pathValue.substring(pathValue.indexOf("/")) + pathValue.substring(pathValue.lastIndexOf("/"));
        }

        if (StringUtils.isEmpty(currentViewPrefix)) {
            currentViewPrefix = this.entityClass.getSimpleName();
        }

        return currentViewPrefix;
    }
	/**
	 * 增加了@ModelAttribute的方法可以在本controller方法调用前执行,可以存放一些共享变量,如枚举值,或是一些初始化操作
	 */

	// @ModelAttribute("")
	public void init(Model model) {
		// model.addAttribute("now", new Date());
	}


	/**
	 * 获取分页 page 对象
	 * @param request
	 * @return
	 */
//	public Page<T> newPage(HttpServletRequest request) {
//		// ==获取分页信息
//	 return 	newPage(request, "id", "desc");
//	}
	/**
	 * 指定默认的排序字段和方法 返回page分页对象
	 * @param request
	 * @param defaultOrder
	 * @param defaultSort
	 * @return
	 */
//	public Page<T> newPage(HttpServletRequest request,String defaultOrder,String defaultSort) {
//		// ==获取分页信息
//
//		String str_pageIndex = request.getParameter("pageIndex");
//		int pageIndex = NumberUtils.toInt(str_pageIndex, 1);
//		String order = request.getParameter("order");
//		String sort = request.getParameter("sort");
//
//		if (StringUtils.isBlank(order)) {
//			order = defaultOrder;
//		}
//		if (StringUtils.isBlank(sort)) {
//			sort = defaultSort;
//		}
//
//		if (StringUtils.isBlank(order)) {
//			order = "id";
//		}
//		if (StringUtils.isBlank(sort)) {
//			sort = "desc";
//		}
//
//		PageInfo
//		Page<T>
//		page.setOrder(order);
//		page.setSort(sort);
//		return page;
//	}
	
	

}
